package com.github.shiqiyue.blog.markdown.config.redis;

import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.shiqiyue.blog.markdown.config.ApplicationConfig;

/***
 * redis 配置类
 * 
 * @author wwy
 *
 */
@EnableConfigurationProperties(ApplicationConfig.class)
@Configuration
public class RedisConfiguration implements ApplicationContextAware {
	
	private ApplicationContext applicationContext;
	
	private ApplicationConfig platformConfig;
	
	public RedisConfiguration(ApplicationConfig platformConfig) {
		this.platformConfig = platformConfig;
	}
	
	/***
	 * redisson 的 spring cache CacheManager 实现
	 * 
	 * @param redissonClient
	 * @return
	 * @throws IOException
	 */
	@Bean
	CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
		return new RedissonSpringCacheManager(redissonClient, "classpath:/cache-config.yml");
	}
	
	/***
	 * redisson 客户端
	 * 
	 * @return
	 * @throws IOException
	 */
	@Bean(destroyMethod = "shutdown")
	RedissonClient redisson() throws IOException {
		Config config = Config.fromYAML(
				applicationContext.getResource(platformConfig.getRedis().getConfigFilePath()).getInputStream());
		return Redisson.create(config);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
